package email

import (
	"crypto/tls"
	"fmt"
	"log"
	"net"
	"net/smtp"
)

// 邮件发送成功
func SendEmail(config SmtpConfig, mailInfo MailInfo) error {
	addr := fmt.Sprintf("%s:%s", config.Host, config.Port)
	auth := smtp.PlainAuth(config.Id, config.Username, config.Password, config.Host)
	client, err := Dial(addr)
	if err != nil {
		log.Println("创建smpt client error:", err)
		return err
	}
	defer client.Close()

	if auth != nil {
		if ok, _ := client.Extension("AUTH"); ok {
			if err = client.Auth(auth); err != nil {
				log.Println("Error during AUTH", err)
				return err
			}
		}
	}
	if err := client.Mail(config.Username); err != nil {
		return err
	}

	for _, addr := range mailInfo.To {
		if err := client.Rcpt(addr); err != nil {
			return err
		}
	}
	writer, err := client.Data()

	if err != nil {
		return err
	}
	if mailInfo.From == "" {
		mailInfo.From = fmt.Sprintf("%s<%s>", config.FromPrefix, config.Username)
	}

	_, err = writer.Write([]byte(mailInfo.GetMessage()))
	if err != nil {
		return err
	}

	err = writer.Close()
	if err != nil {
		return err
	}
	return nil

}
func Dial(addr string) (*smtp.Client, error) {
	conn, err := tls.Dial("tcp", addr, nil)
	if err != nil {
		log.Println("Dialing Error:", err)
		return nil, err
	}
	//分解主机端口字符串
	host, _, _ := net.SplitHostPort(addr)
	return smtp.NewClient(conn, host)
}
